import store from '../store';
import shared from '../shared';
import { getToken } from '../utils/auth';

var WS = null;
var global_callback = null;

// if(WS){
//   WS.onopen = function (e) {
//     console.log(1);
//     onOpen (e, token);
//   };

//   WS.onerror = function (e) {
//     onError (e);
//   };

//   WS.onclose = function (e) {
//     onClose (e);
//   };
// }

function initWs(){
  var token = store.state.user.token;
  if(!token){
    token = getToken();
  }
  
  WS = new WebSocket(shared.chatServer() + '/Chat?token=' + token);
  
  WS.onopen = function (e) {
    onOpen (e, token);
  };

  WS.onerror = function (e) {
    onError (e);
  };

  WS.onclose = function (e) {
    onClose (e);
  };

  return WS;
}

function onOpen(event, token){
  // let strMsg = {'type': 0, 'token': token};
  // let msg = JSON.stringify(strMsg);
  // send(msg);
}
function onError(event){
  if(global_callback){
    global_callback(event);
  }
  console.log('ERROR');
  // alert('聊天服务器未连接，聊天暂不可用，请联系管理员');
}
function onClose(event){
  console.log('CLOSED');
}
function send(message, callback) {
  global_callback = callback;
  if (WS.readyState === WS.OPEN) {
    WS.send(message);
  } else if (WS.readyState === WS.CONNECTING) {
    setTimeout(function () {
      WS.send(message);
    }, 300);
  } else {
    initWs();
    setTimeout(function () {
      WS.send(message, callback);
    }, 500);
  }
  // WS.send(message);
}

export {WS, initWs, send};
// export default WS;